var showMessage = function (title, message, color) {
    var color = typeof color !== 'undefined' ? color : '#659265';
    return $.smallBox({
        title  : title,
        content: message,
        color  : color,
//            iconSmall: "fa fa-times fa-2x fadeInRight animated",
        timeout: 4000
    });
};
function getTree(nodes, parentId) {
    var nodeStack = [];
    for (var i in nodes) {
        var currentNode = nodes[i];
        if (currentNode.parent_id == parentId) {
            var children = getTree(nodes, currentNode.id)
            if (children.length > 0) {
                nodeStack.push({"id": currentNode.id, "text": currentNode.text, "children": children});
            } else {
                nodeStack.push({"id": currentNode.id, "text": currentNode.text});
            }
        }
    }

    return nodeStack;
}
var newSelectNodesData = getTree(nodeCategories, 0);

function initializeNestableList() {
    var saveAllTree = function (nestableElement) {
        var treeUpadateData = {"treeData": nestableElement.nestable('serialize')};
        var $inProgressContainer = $('#updatingInProgressContainer');
        $inProgressContainer.removeClass('hidden');

        var ajaxDeferred = $.ajax({
            data : treeUpadateData,
            type : 'POST',
            url  : '/cp/catalog/save-all',
            cache: false
        });
        ajaxDeferred.always(function (jqXHR, textStatus) {
            $inProgressContainer.addClass('hidden');
        });
        ajaxDeferred.done(function (data, textStatus, jqXH) {
            var code = typeof data.code !== 'undefined' ? parseInt(data.code) : parseInt(0);
            if ("success" == textStatus && code > 0) {
                showMessage('Обновление каталога', 'Разделы успешно обновлены');
            } else {
                showMessage('Обновление каталога', 'При обновлении каталога произошла ошибка', '#C46A69');
            }
        });

    };

//    var updateOutput = function (e) {
//        var list = e.length ? e : $(e.target),
//            output = list.data('output')
//            ;
//
//        if (window.JSON) {
//            output.val(window.JSON.stringify(list.nestable('serialize')));
//            //, null, 2));
//        } else {
//            output.val('JSON browser support required for action.');
//        }
//    };

    var $nestable = $('#nestable');
    $nestable.nestable({group: 1});//.on('change', updateOutput);
//    updateOutput($nestable.data('output', $('#nestable-output')));

    $('#nestable-menu').on('click', function (e) {
        var target = $(e.target), action = target.data('action');
        if (action === 'expand-all') {
            $('.dd').nestable('expandAll');
        }
        if (action === 'collapse-all') {
            $('.dd').nestable('collapseAll');
        }
        if (action === 'save-all') {
            saveAllTree($nestable);
        }
    });
}

/**
 * Инициализируем форму с сабмит-колбэком, где будем брать данные у самерноута и пихать их в нашу невидимую textarea
 */
function initializeForm() {
    var $parentIdSelect2 = $('#newSectionParentId');

    $parentIdSelect2.select2({
        allowClear: true,
        width     : '100%',
        data      : newSelectNodesData
    });
    attachSummernoteToElementInForm('#newSectionForm', '#newSectionDescription', '/cp/files/file-to-sections');

    $parentIdSelect2.select2('val', newSelectNodesData[0].id);
}


var initializeEditForm = (function () {
    var $form = $('#editSectionForm'),
        $header = $form.find('#editSectionHeader'),
        $name = $form.find('#editSectionName'),
        $parentId = $form.find('#editSectionParentId'),
        $sectionId = $form.find('#editSectionId'),
        $wygDescription = null,
        $widget = $form.closest('div.widget-body'),
        $deleteButton = $('#deleteNodeRecursive'),
        $inProgressContainer = $('#updatingInProgressContainer'),
        $currentNodeDiv = null,
        nodeClickAjax = $.Deferred().resolve()
        ;

    $form.setData = function (nodeData) {
        $header.text(nodeData.name).removeClass('hidden');
        $name.val(nodeData.name);
        $parentId.select2('val', nodeData.parent_id.$id);
        $wygDescription.code(nodeData.description);
        $sectionId.val(nodeData._id.$id);
        $deleteButton.removeClass('disabled');
    };

    $form.onNodeClick = function (event) {
        event.stopPropagation();
        if ('resolved' != nodeClickAjax.state()) {
            return false; //think about it in "cancelling ajax" terms
        }

        var $target = $(event.target),
            $li = $target.closest('li'),
            sectionId = $li.data('id'),
            sectionDataUrl = '/cp/catalog/get-section-data/' + sectionId;
        ;
        $currentNodeDiv = $target;
        if (0 == $li.data('parent_id')) {
            return false;
        }

        nodeClickAjax = $.ajax({
            type      : 'GET',
            url       : sectionDataUrl,
            cache     : false,
            beforeSend: function (xhr) {
                $deleteButton.addClass('disabled');
                $widget.addClass('widget-body-ajax-loading');
            }
        }).done(function (response, textStatus, jqXH) {
            var code = typeof response.code !== 'undefined' ? parseInt(response.code) : parseInt(0);
            if ("success" == textStatus && code > 0) {
                $form.setData(response.data);
            }
            $widget.removeClass('widget-body-ajax-loading');
        });
    };
    $form.onDeleteButtonClick = function (event) {
        if (!$sectionId.val()) {
            return false;
        }
        var deleteSectionUrl = '/cp/catalog/delete-section/' + $sectionId.val();
        $.SmartMessageBox({
            title : 'Подтверждение на удаление раздела каталога<br/><span class="txt-color-greenLight">"{section}"</span>'.supplant({ "section" : $header.text() }),
            content : 'Удаляем: <span class="txt-color-redLight">рекурсивно (вместе с дочерними разделами)</span>',
            buttons : '[No][Yes]'
        }, function(ButtonPressed) {
            if ('Yes' == ButtonPressed) {
                location.href = deleteSectionUrl;
            }
        });

        event.preventDefault();
    };
    $form.onInitialize = function (event) {
        $parentId.select2({
            allowClear: true,
            width     : '100%',
            data      : newSelectNodesData
        });
        $wygDescription = attachSummernoteToElementInForm('#editSectionForm', '#editSectionDescription', '/cp/files/file-to-sections');
    };
    $form.onSubmit = function(event) {
        event.preventDefault();

        $inProgressContainer.removeClass('hidden');
        var updateSectionUrl = '/cp/catalog/update-section/';// + $sectionId.val();
        var ajaxDeferred = $.ajax({
            data : $form.serializeArray(),
            type : 'POST',
            url  : updateSectionUrl,
            cache: false
        });
        ajaxDeferred.always(function (jqXHR, textStatus) {
            $inProgressContainer.addClass('hidden');
        });
        ajaxDeferred.done(function (response, textStatus, jqXH) {
            var code = typeof response.code !== 'undefined' ? parseInt(response.code) : parseInt(0);
            if ("success" == textStatus && code === 1) {
                showMessage('Обновление раздела каталога', 'Раздел успешно обновлён');
                $currentNodeDiv.text(response.data.name);
            } else {
                showMessage('Обновление раздела каталога', 'При обновлении раздела каталога произошла ошибка', '#C46A69');
            }
        });
    }

    $form.on('initialize', $form.onInitialize);
    $form.on('submit', $form.onSubmit);
    $('.dd-item').on('click', '.dd3-content.cursor', $form.onNodeClick);
    $deleteButton.on('click', $form.onDeleteButtonClick);

    $form.triggerHandler('initialize');
});

function onNodeClick(event) {
    var $ajaxDeferred = $.get(sectionDataUrl);

    $ajaxDeferred.done();
    console.log($target, sectionId);
}

$(document).ready(function () {
    initializeForm();
    initializeEditForm();
    initializeNestableList();
});